#ifndef __main_c__
#define __main_c__

#include <zneo.h>
#include <sio.h>
#include <stdio.h>

#include "led.h"
#include "scanmatrix.h"

#define PAINMASK 0x07 // use PA[0..2] as detector
#define PBINMASK 0xFF // use PB[0..7] as detector
#define PHINMASK 0x0F // use PH[0..3] as detector

#define PDOUTMASK 0x00

void main (void) {

	unsigned char a, b, h;
	unsigned int comb, _comb;
	unsigned char i;

	InitLEDs();

	// set output pins
	PDDD &= PDOUTMASK;
	// another 2 pins remain...

	// set input pins.
	PBDD |= PBINMASK;
	PHDD |= PHINMASK;
	PADD |= PAINMASK;

	// enable pullup on input pins
	PBPUE |= PBINMASK;
	PHPUE |= PHINMASK;
	PAPUE |= PAINMASK;

    init_uart(_UART0, _DEFFREQ, 9600); 
	printf("Key Detect\n");

	//EI();

	a=0;
	b=0;
	h=0;
	comb = 0;

	i=0;

	PDOUT = ~0x01;

	while (1) {
		_comb = comb;

		PDOUT = ~(0x01<<i);

		a = (PAIN & PAINMASK);
		b = (PBIN & PBINMASK);
		h = (PHIN & PHINMASK);
		
		comb = b;
		comb += 0x100 * h;
		comb += 0x1000 * a;

		if (comb != _comb) {
			if (~comb & 0x3FFF) {
				printf("-----\n");
				printf("i: %x\n", i);
				//printf("b: %x\n", (~b & PBINMASK));
				//printf("a: %x\n", (~a & PAINMASK));
				//printf("h: %x\n", (~h & PHINMASK));
				printf("c: %x\n", (~comb & 0x7FFF));
			}
		}
		i = ((i+1)%8);
	}
}


#endif